import axios from 'axios'
import store from '@/store'
import router from '@/router'
// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        //
      }
    }
    return config
  }
  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  // 校验用户登录状态
  checkLoginStatus() {
    return axios.get('http://api.iosp.xjyt.petrochina/iam/v1/user/self', {
      headers: {
        'Authorization': 'Bearer ' + token  // 实际的用户token
      }
    });
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // console.log("开始拦截请求")
      //获取token设置请求头
      if (localStorage.getItem('tagNaveList')) {
        const token = (JSON.parse(localStorage.getItem('tagNaveList'))[0].query.access_token)
        // console.log("token:", token)
        config.headers.Authorization = 'Bearer ' + token
      }
      // if(localStorage.getItem('tagNaveList')){
      // const token = (JSON.parse(localStorage.getItem('tagNaveList'))[0].query.access_token);
      // const token=store.state.token
      // const token = new URLSearchParams(window.location.search).get('access_token')
      // console.log("token:", token)
      // axios.get('http://11.71.3.110:30010/iam/v1/users/self', {
      //   headers: {
      //     'Authorization': 'Bearer ' + token  // 实际的用户token
      //   }
      // }).then(response => {
      //   // 如果返回用户信息，则表示token 有效
      //   // console.log('用户信息：', response.data);
      //   // 带着用户信息去请求菜单
      //   axios.get(`http://11.71.3.110:30010/iam/v1/menus/tree?labels=GCYRDCHQKF&lang=${response.data.language}&roleId=${response.data.currentRoleId}&unionLabel=false`,{
      //     headers: {
      //       'Authorization': 'Bearer ' + token  // 实际的用户token
      //     }
      //   }
      //   ).then((res)=>{
      //     let account=response.data
      //     account.menus=res.data
      //     console.log(res.data[0].subMenus)
      //     if(account){
      //       sessionStorage.setItem('account',JSON.stringify(account))
      //     }

      //   })


      // }).catch(error => {
      //   // 如果报错，则代表token失效，需要重新登录
      //   console.error('校验失败：', error);
      //   // 进行重新登录操作
      //   window.location.href = 'http://11.71.3.110:30011/public/unauthorized'
      // });
      // if (token) {
      //   console.log("token放消息头")
      //   config.headers["Authorization"] = `Bearer ${token}`;
      // }



      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {

      // let isExcel=res.request.responseURL.slice(res.request.responseURL.length-5,res.request.responseURL.length);
      //  //请求地址后5位为Excel表示为导出接口
      //  if(isExcel==='Excel'){
      //   res.headers["responseType"] = 'blob';
      //  }
      // console.log('respons:',res,isExcel)
      this.destroy(url)
      const { data, status } = res
      if (data.message === '用户信息验证失败') {
        //重定向到它的登录失效页面
        // window.location.href = 'http://11.71.3.110:30010/oauth/login'
        window.location.href = 'http://11.71.3.110:30011/public/unauthorized'
      }
      return { data, status }
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: { responseURL: config.url }
        }
      }
      addErrorLog(errorInfo)
      return Promise.reject(error)
    })
  }
  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
